package com.qqtop10.manager.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.qqtop10.manager.model.temp.ShopTemp;
import com.qqtop10.manager.utils.http.entity.CustomerService;
import com.qqtop10.manager.utils.http.entity.OauthBody;
import com.qqtop10.manager.utils.http.entity.OauthBody.OauthInfo;
import com.qqtop10.manager.utils.http.entity.SellerClassify;
import com.qqtop10.manager.utils.http.help.ParseHelper;

/**
 * 小能客服请求相应帮助类
 * 
 * @author cathy
 *
 */
public class HttpHelper {
	// 小能客服URL
	private static final String CUSTOMERSERVICEURL = "https://hz-v7.ntalker.com/api/";
	// 获取令牌URL
	private static final String GETTOKEN = CUSTOMERSERVICEURL + "OauthCredentials/oauth";
	// 刷新令牌URL
	private static final String REFRESHTOKEN = CUSTOMERSERVICEURL + "OauthCredentials/refresh";
	// 创建商户URL
	private static final String CREATESELLERS = CUSTOMERSERVICEURL + "Sellers/Sellers";
	// 获取商户分类
	private static final String CLASSIFY = CUSTOMERSERVICEURL + "SellerClassify/SellerClassify/siteid/de_1000";

	// 应用ID
	private static final String CLIENTID = "6ce79628";
	// 应用秘钥
	private static final String CLIENTSECRET = "c091e0a84f";
	// 小能客服api的授权码token
	private static final String OAUTHTOKEN = "f543288a4780b091d2ba4bc1e1f573f8";
	// 授权类型
	private static final String[] GRANTTYPE = { "code", "refreshtoken" };

	/**
	 * 
	 * @return 组装获取令牌接口的URL参数
	 */
	private static String buildOauthTokenUrl() {
		StringBuilder requestUrl = new StringBuilder(GETTOKEN);
		requestUrl.append("/client_id/");
		requestUrl.append(CLIENTID);
		requestUrl.append("/client_secret/");
		requestUrl.append(CLIENTSECRET);
		requestUrl.append("/code/");
		requestUrl.append(OAUTHTOKEN);
		requestUrl.append("/grant_type/");
		requestUrl.append(GRANTTYPE[0]);
		return requestUrl.toString();
	}

	public static String buildRefreshOauthTokenUrl(String refreshToken) {
		StringBuilder refreshUrl = new StringBuilder(REFRESHTOKEN);
		refreshUrl.append("/client_id/");
		refreshUrl.append(CLIENTID);
		refreshUrl.append("/client_secret/");
		refreshUrl.append(CLIENTSECRET);
		refreshUrl.append("/refresh_token/");
		refreshUrl.append(refreshToken);
		refreshUrl.append("/grant_type/");
		refreshUrl.append(GRANTTYPE[1]);
		return refreshUrl.toString();
	}

	/**
	 * 
	 * @return 获取接口的令牌数据
	 */
	public static String getOauthToken() {
		BufferedReader br = null;
		String responseData = null;
		try {
			URL url = new URL(buildOauthTokenUrl());
			URLConnection openConnection = url.openConnection();
			InputStream inputStream = openConnection.getInputStream();
			br = new BufferedReader(new InputStreamReader(inputStream));
			responseData = br.readLine();
			responseData = responseData.replaceFirst("O", "o");
			return responseData;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				} finally {
					br = null;
				}
			}
		}
		return null;
	}

	public static String getClassify(String accessToken) {
		HttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(CLASSIFY);
		httpGet.setHeader("access-token", accessToken);
		httpGet.setHeader(new BasicHeader("Accept", "application/json;charset=utf-8"));
		try {
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String response = httpClient.execute(httpGet, responseHandler);
			return response;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("deprecation")
	public static String createShop(String token, int id, ShopTemp shopTemp) {
		try {
			HttpClient httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(CREATESELLERS);
			HttpParams httpParams = httpPost.getParams();
			httpParams.setParameter("http.protocol.conent-charset", HTTP.UTF_8);
			httpParams.setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			httpParams.setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			httpParams.setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
			List<NameValuePair> params = new ArrayList<>();
			params.add(new BasicNameValuePair("classify_id", "" + id));
			params.add(new BasicNameValuePair("name", shopTemp.getName()));
			params.add(new BasicNameValuePair("administrator", shopTemp.getAccount()));
			params.add(new BasicNameValuePair("password", "t10mall"));
			params.add(new BasicNameValuePair("level", "1"));
			httpPost.setHeader("access-token", token);
			httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			String content = EntityUtils.toString(entity);
			return content;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static OauthInfo getOauthInfo() {
		String token = HttpHelper.getOauthToken();
		OauthBody oauthBody = ParseHelper.parseOauthTokenData(token);
		OauthInfo oauthInfo = oauthBody.getOauthInfo();
		return oauthInfo;
	}

	public static List<SellerClassify> getSellerClassifyList(String token) {
		String data = getClassify(token);
		List<SellerClassify> list = ParseHelper.parseClassify(data);
		return list;
	}

	public static CustomerService getCustomerServiceInfo(String token, int id, ShopTemp shopTemp){
		String data = createShop(token, id, shopTemp);
		return ParseHelper.parseCustomService(data);
	}

}
